<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="BOM编号" prop="bomCode">
        <el-input v-model="queryParams.bomCode" placeholder="请输入BOM编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:bom:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:bom:edit']">修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:bom:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:bom:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="" align="center" prop="id" /> -->
      <el-table-column label="BOM编号" align="center" prop="bomCode" />
      <el-table-column label="成本" align="center" prop="totalCost" >
        <template slot-scope="scope">
          {{ (scope.row.totalCost).toFixed(2)+'元' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:bom:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:bom:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改产品BOM对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="BOM编码" prop="bomCode">
          <el-input :disabled="noModify" v-model="form.bomCode" placeholder="请输入BOM编号" />
        </el-form-item>
        <el-form-item label="绑定产品" prop="proId">
          <el-select :disabled="noModify" v-model="form.proId" filterable placeholder="请选择">
            <el-option v-for="item in proinfoselectoption" :key="item.id" :label="item.proName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

        <el-divider>原 料 列 表</el-divider>
        <el-button style="margin-bottom: 10px;" type="primary" @click="bommtradd">添 加</el-button>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
            <el-table-column label="原料名称" align="center" prop="mtrName">
              <template slot-scope="scope">
                <el-select v-model="scope.row.id" filterable placeholder="请选择"
                  @change="(option) => mtrchang(option, scope.$index)">
                  <el-option v-for="item in bomselectoption" :key="item.id" :label="item.mtrName" :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="原料编码" align="center" prop="mtrCode"/>
            <el-table-column label="原料价格" align="center" prop="cost">
              <template slot-scope="scope">
                {{ scope.row.cost==undefined?'0元':scope.row.cost+'元' }}
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <a-input-number id="inputNumber" v-model:value="scope.row.mtrQuantity" :min="0" :precision="0"/>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="bommtradd(scope.$index, scope.row)"
                  v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="bommtrdel(scope.$index)"
                  v-hasPermi="['mes:proinfo:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, updateBom } from "@/api/mes/bom";
import { listMtrinfo } from "@/api/mes/mtrinfo"
import { editProBomAndMtrs } from "@/api/mes/proinfo";
import { listProinfo } from "@/api/mes/proinfo";

export default {
  name: "Bom",
  data() {
    return {
      //能否修改
      noModify: false,
      /**
       * 产品下拉框数据
       */
      proinfoselectoption: [],
      /**
       * bom原料下拉框数据
       */
      bomselectoption: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品BOM表格数据
      bomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomCode: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bomCode: [
          { required: true, message: 'BOM编码不能为空', trigger: 'change' }
        ],
        proId: [
          { required: true, message: '绑定产品不能为空', trigger: 'change' }
        ],

      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 下拉框改变
     * @param {选项值} option 
     */
    mtrchang(option, index) {
      let ss = this.bomselectoption.find(item => item.id == option)
      this.form.mtrs[index].mtrName = ss.mtrName
      this.form.mtrs[index].mtrCode = ss.mtrCode
      this.form.mtrs[index].cost = ss.cost
    },
    /**
     * 删除原料
     * @param {下标} index 
     */
    bommtrdel(index) {
      this.form.mtrs.splice(index, 1)
    },
    /**
     * 添加原料
     * @param {下标} index 
     * @param {行数据} row 
     */
    bommtradd(index, row) {
      if (index != undefined) {
        this.form.mtrs.splice(index + 1, 0,
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            id: null,
            houId: null,
            mtrCode: null,
            mtrName: null,
            mtrQuantity: 0,
            mtrProType: 0
          })
      } else {
        this.form.mtrs.push(
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            id: null,
            houId: null,
            mtrCode: null,
            mtrName: null,
            mtrQuantity: 0,
            mtrProType: 0
          })
      }
    },
    /** 查询产品BOM列表 */
    getList() {
      this.loading = true;
      listBom(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listMtrinfo().then((res) => {
        this.bomselectoption = res.rows
        console.log("🚀 ~ file: index.vue:175 ~ listMtrinfo ~ this.bomselectoption:", this.bomselectoption)
      })
      listProinfo().then((res) => {
        this.proinfoselectoption = res.rows
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.proinfoselectoption:", this.proinfoselectoption)
      })

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        proId: null,
        mtrId: null,
        bomCode: null,
        mtrs: [],
        // mtrQuantity: null,

        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.noModify = false;
      this.title = "添加产品BOM";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.noModify = true;
      const id = row.id || this.ids
      getBom(id).then(response => {
        this.form = response.data;
        this.form.id = id;
        this.open = true;
        this.title = "修改产品BOM";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          if (this.form.mtrs.findIndex(e => { return e.id == null }) != -1 || this.form.mtrs.length == 0) {
            this.$modal.msgError("请添加原料或将原料信息填写完整");
          } else {
            if (this.form.id != null) {
              updateBom(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBom(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品BOM编号为"' + ids + '"的数据项？').then(function () {
        return delBom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/bom/export', {
        ...this.queryParams
      }, `bom_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
